
/**
 * 封封微信的的request
 */
function request(url, data = {}, method) {
  return new Promise(function(resolve, reject) {
    wx.showLoading({
      title: '加载中',
    })
    // console.log(cood)
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Cookie': wx.getStorageSync("cookie"), //是否登录
        'Content-Type': 'application/json', // 默认值  //data里面参数给服务器的编码格式 get
        'content-type': 'application/x-www-form-urlencoded', // 默认值  //data里面参数给服务器的编码格式 post
      },
      success: function(res) {
        console.log("success");
        // console.log(cookie)
        if (res.statusCode == 200) {
          resolve(res);

        } else {
          reject(res.errMsg);
        }

      },
      fail: function(err) {
        reject(err)
        console.log("failed")
      }
    })
    wx.hideLoading()
  });
}
/**
 * 封封微信的的wx.uploadFile
 */
function uploadImage(url, data, type, responseType) {
  if (Array.isArray(data)) {
    return new Promise((resolve, reject) => {
      if (data.length > 0) {
        var promiseList = [];
        // wx.showLoading({
        //   title: '加载中',
        // })
        for (var i = 0; i < data.length; i++) {
          promiseList[i] = new Promise((resolve, reject) => {
            wx.uploadFile({
              url: url, //仅为示例，非真实的接口地址
              filePath: data[i],
              name: "file",
              formData: {
                type: type,
                responseType: responseType
              },
              header: {
                'Cookie': wx.getStorageSync("cookie"), //是否登录
                'content-type': 'multipart/form-data' //图片上传的头部
              },
              success: function(res) {
                if (res.statusCode == 413) {
                  wx.showModal({
                    title: '提示',
                    content: '图片太大请重新上传',
                    showCancel: false,
                  })
                } else {
                  console.log("成功")
                  console.log(res)
                  console.log(res.data)
                  var res = JSON.parse(res.data);
                  resolve(res);
                }
              },
              fail: function(error) {
                reject(error);
              }
            })
            // wx.hideLoading()
          });
        }
        Promise.all(promiseList)
          .then(function(result) {
            resolve(result);
          })
          .then(function(error) {
            reject(error);
          })
      } else {
        reject('传参有误，请传数组格式');
      }
    })
  } else {
    wx.showModal({
      title: '提示',
      content: '错误',
      showCancel: true,
    })
  }

}
module.exports = {
  request,
  uploadImage
}